package iscript.gameFramework.IsoLibarys 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import flash.utils.setTimeout;
	import iscript.coreFramework.data.datatable.DataTable;
	import iscript.coreFramework.displays.Element;
	import iscript.coreFramework.math.Point2D;
	import iscript.coreFramework.reflect.getClassName;
	import iscript.gameFramework.IsoLibarys.config.IsoConfig;
	import iscript.gameFramework.IsoLibarys.data.IsoBaseData;
	import iscript.gameFramework.IsoLibarys.data.IsoBound;
	import iscript.gameFramework.IsoLibarys.data.IsoBuilderList;
	import iscript.gameFramework.IsoLibarys.data.IsoSpriteBuffer;
	import iscript.gameFramework.IsoLibarys.display.IsoSprite;
	import iscript.gameFramework.IsoLibarys.display.IsoTile;
	import iscript.gameFramework.IsoLibarys.events.IsoViewEvent;
	import iscript.gameFramework.IsoLibarys.IsoScene;
	import iscript.gameFramework.IsoLibarys.math.IsoMath;
	import iscript.gameFramework.IsoLibarys.state.IsoSpriteState;
	import iscript.gameFramework.IsoLibarys.state.IsoTileState;
	import iscript.gameFramework.IsoLibarys.state.IsoViewState;
	import iscript.gameFramework.IsoLibarys.util.IsoUtil;

	
	public class IsoView extends Sprite
	{
		private var _textCoordVisible:Boolean;
		private var _gridVisible:Boolean;
		private var _state:String = IsoViewState.NORMAL;
		private var _isoScene:IsoScene;
		private var _isoData:DataTable;
		 
		private var _previewSprite:IsoSprite;
		private var _isoPreviewContainer:Sprite;		
	    	
		private var _isoGridSprite:Sprite;
		private var _isoGidList:Dictionary;	
         
		private var _isoBuildSprite:Sprite;
		private var _isoBuilderList:IsoBuilderList;
		 
		 
		 
		public function IsoView(isoscene:IsoScene)
		{
	 
			
			_isoGridSprite = new Sprite();
			addChild(_isoGridSprite);
			Element.unActive(_isoGridSprite);
			
			_isoBuildSprite = new Sprite();
			addChild(_isoBuildSprite);
			Element.unActive(_isoBuildSprite);
			
			
			/*_isoPreviewContainer = new Sprite();
			addChild(_isoPreviewContainer);
			Element.unActive(_isoPreviewContainer);*/		
			
			_isoGidList = new Dictionary();
			
			_isoScene = isoscene; 			 
			_isoData = DataTable(_isoScene.getGridData()).clone();	
			_createGrid();	
			
			_isoBuilderList = new IsoBuilderList(_isoBuildSprite,_isoData);
			
			_editBound = _isoScene.getIsoSceneBound();
			
			this.setState(IsoViewState.NORMAL);
			addEventListener(Event.ADDED_TO_STAGE, _addToStageLogic);
			addEventListener(Event.REMOVED_FROM_STAGE, _removeFromStageLogic);			
		}
		
		public function  getIsoScene():IsoScene { return _isoScene;}
		 
		private var _editBound:IsoBound;
		public function setEditBound(bound:IsoBound):void {
			    _editBound = bound;
			}
		public function getEditBound():IsoBound {
			    return _editBound;
			}
		 
		/**
		 * IsoViewState class
		 * @param	state
		 */
		public function setState(state:String):void { 
			   // 设置状态对其他IsoView做一个复位的处理
			   //_isoScene.isoViewManager.getUnActiveIsoView
			    
			    switch(state) {
				case IsoViewState.NORMAL:
					 fillReset();
					 gridVisible = false;
					 if (_state == IsoViewState.MOVE) {
						     
						     trace(_previewSprite);
						 }
					 
					 
					 removePreviewItem();
					 for (var i:int = 0; i <this.getAllIsoSprite().length; i++) 
					 {
					   IsoSprite(this.getAllIsoSprite()[i]).getGround().visible = false;
					 }
					 
					break;
				case IsoViewState.BUILD:
					this.gridVisible = true;
					//this.textCoordVisible = false;
					break;
				case IsoViewState.MOVE:
					this.gridVisible = true;
					break;
					
				}
				_state = state;
			}		 
		public function getState():String { return _state; }
		
		public function get Data():DataTable { return _isoData; }
		public function getAllIsoSprite():Vector.<IsoSprite> { return _isoBuilderList.getAllIsoSprite(); }
			
		public function get IsoSpriteList():IsoBuilderList {
			  return this._isoBuilderList;
			}
		
		
		private function _addToStageLogic(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, _addToStageLogic);			
		 	stage.addEventListener(MouseEvent.MOUSE_DOWN, _mouseDownLogic);
			stage.addEventListener(MouseEvent.CLICK, _mouseClickLogic);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, _mouseMoveLogic);
		    stage.addEventListener(MouseEvent.MOUSE_UP, _mouseUpLogic);
		}
		
		private function _removeFromStageLogic(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, _removeFromStageLogic);
		 	stage.removeEventListener(MouseEvent.MOUSE_DOWN, _mouseDownLogic);
			stage.removeEventListener(MouseEvent.CLICK, _mouseClickLogic);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, _mouseMoveLogic);
		 	stage.removeEventListener(MouseEvent.MOUSE_UP, _mouseUpLogic);
		}
		
		public function getGrid(row:int, column:int):IsoTile {
			  return _isoGidList[row + "_" + column];
			}
		 
		/**
		 * 是否包含单个或范围格子 [Point2D IsoBound]
		 * @param	data
		 * @return
		 */
		public function containBound(data:Object):Boolean {	
			  return IsoMath.viewContainBound(this, data);
			}
		 
		/**
		 * 加入建筑队列
		 * @param	item
		 */
	/*	public function addBufferIsoSprite(item:IsoSprite):void {
			  addIsoSprite(item);
			 //IsoSpriteBuffer.getInstance().add(this, item);
			 // IsoSpriteBuffer.getInstance().addDelay(this, item, Math.random() * 1500);
			}	*/
			
			
		public function addIsoSprite(item:IsoSprite):void {	
			    if (item == null) return;
			    if ( item.getIsoBound()==null  || !IsoMath.checkIsoBoundOpen(this, item.getIsoBound())) return;
			     _addIsoSprite = item;				 
				 var itemIsoBound:IsoBound = item.getIsoBound();
				 _setBuilder(itemIsoBound);			     
				 _isoBuilderList.addItem(item);	//IsoBuilderList 自动管理排序
				 for (var i:int = 0; i <this.getAllIsoSprite().length; i++) 
				 {
				   IsoSprite(this.getAllIsoSprite()[i]).getGround().visible = false;
				 }
				_previewSprite = null;
				 if ( this.getState() == IsoViewState.BUILD) {
				      this.dispatchEvent(new IsoViewEvent(IsoViewEvent.ADDISOSPRITE));
				  }
		}
		 
		public function removeIsoSprite(item:IsoSprite):void {
			  if (item != null) {
				  removeSpacerData(item.getIsoBound());
				  _removeIsoSprite = item;
				  _removeBuilder(item.getIsoBound());
				  _isoBuilderList.removeItem(item);
				  if (_isoBuildSprite.contains(item))
				  {
					_isoBuildSprite.removeChild(item);
				  }
				  this.dispatchEvent(new IsoViewEvent(IsoViewEvent.REMOVEITEM));
			  }
			}		
			
		/**
		 * 移除占位数据
		 * @param	data
		 */	
		public function removeSpacerData(data:IsoBound):void {
			    var _isoSceneGrid:IsoBaseData;			
				  var isobasedata:IsoBaseData; 
				  for (var i:int = data.topGrid.x; i <=data.bottomGrid.x; i++) 
				  {
					  for (var j:int = data.topGrid.y; j <=data.bottomGrid.y; j++) 
					  {
							_isoSceneGrid = IsoBaseData(_isoData.getCell(i,j.toString()));
							 isobasedata =  new IsoBaseData();
							 isobasedata.Bound = _isoSceneGrid.Bound;
							 isobasedata.IsBuilder = false;
							 isobasedata.IsWalkable = _isoSceneGrid.IsWalkable;
							 _isoData.updateCell(i, j.toString(), isobasedata);
					  }
				  }
			}	
			
		private function _setBuilder(data:Object):void {
			  var _isoSceneGrid:IsoBaseData;			
              var isobasedata:IsoBaseData; 
		       
			  switch(getClassName(data)) {
				    case  "Point2D":
						 var v:Point2D = data as Point2D;
						  	 _isoSceneGrid =IsoBaseData( _isoData.getCell(v.x, v.y.toString()) );
							 isobasedata =  new IsoBaseData();
							 isobasedata.Bound = _isoSceneGrid.Bound;
							 isobasedata.IsBuilder = true;
							 isobasedata.IsWalkable = _isoSceneGrid.IsWalkable;
							 _isoData.updateCell(v.x, v.y.toString(), isobasedata);
						 
						break;
				    case "IsoBound":
						 data = IsoBound(data);
				        for (var i:int = data.topGrid.x; i <=data.bottomGrid.x; i++) 
						  {
							  for (var j:int = data.topGrid.y; j <=data.bottomGrid.y; j++) 
							  {
								    _isoSceneGrid = IsoBaseData(_isoData.getCell(i,j.toString()));
									 isobasedata =  new IsoBaseData();
									 isobasedata.Bound = _isoSceneGrid.Bound;
									 isobasedata.IsBuilder = true;
									 isobasedata.IsWalkable = _isoSceneGrid.IsWalkable;
									 _isoData.updateCell(i, j.toString(), isobasedata);
								 
							  }
						  }
					break;
				}
			}	
			
		private function  _allowBuilder(data:Object):Boolean {
			    var result:Boolean = true;   
				var _isoSceneGrid:IsoBaseData;	
				  switch(getClassName(data)) {
						case  "Point2D":
							 var v:Point2D = data as Point2D;
								 _isoSceneGrid =IsoBaseData( _isoData.getCell(v.x, v.y.toString()) );
								 if (_isoSceneGrid.IsBuilder) result = false;								 
							break;
						case "IsoBound":
							 data = IsoBound(data);
							for (var i:int = data.topGrid.x; i <=data.bottomGrid.x; i++) 
							  {
								  for (var j:int = data.topGrid.y; j <=data.bottomGrid.y; j++) 
								  {
										_isoSceneGrid = IsoBaseData(_isoData.getCell(i,j.toString()));
										 if (_isoSceneGrid.IsBuilder) result = false;
									
								  }
							  }
						break;
					}
					
				return result;
			}
			
		private function _removeBuilder(data:Object):void {
              var _isoSceneGrid:IsoBaseData;	
			  var isobasedata:IsoBaseData;
			  switch(getClassName(data)) {
				    case  "Point2D":
						 var v:Point2D = data as Point2D;
						  	 _isoSceneGrid = IsoBaseData( _isoData.getCell(v.x, v.y.toString()) );
							 
							 isobasedata =  new IsoBaseData();
							 isobasedata.Bound = _isoSceneGrid.Bound;
							 isobasedata.IsBuilder = false;
							 isobasedata.IsWalkable = _isoSceneGrid.IsWalkable;

							 _isoData.updateCell(v.x, v.y.toString(),isobasedata);
						break;
				    case "IsoBound":
						 data = IsoBound(data);
				        for (var i:int = data.topGrid.x; i <=data.bottomGrid.x; i++) 
						  {
							  for (var j:int = data.topGrid.y; j <=data.bottomGrid.y; j++) 
							  {
								    _isoSceneGrid = IsoBaseData(_isoData.getCell(i,j.toString()));
									isobasedata =  new IsoBaseData();
									isobasedata.Bound = _isoSceneGrid.Bound;
									isobasedata.IsBuilder = false;
									isobasedata.IsWalkable = _isoSceneGrid.IsWalkable;
									_isoData.updateCell(i,j.toString(),isobasedata);
							  }
						  }
					break;
				}
			}
			
		/*******Tile*************************************************/	
		private  function _createGrid():void {
			   for (var i:int = 0; i < _isoData.RowCount; i++)
				{
					var datarow:Dictionary = new Dictionary();
					for (var j:int = 0; j < _isoData.ColumnCount; j++) 
					{
						var _rect:Rectangle =  IsoMath.getGridRectangle(this,new Point2D(i,j));
						var _isotile:IsoTile = new IsoTile(i, j, _rect);
							_isotile.x = _rect.x;
							_isotile.y = _rect.y;
							_isoGridSprite.addChild(_isotile);
							_isoGidList[_isotile.row + "_" + _isotile.column] = _isotile;
					}	
				}
			}
		
		public function fill(data:Object):void {
			  switch(getClassName(data)) {
				  case "Point2D":
					  var v:Point2D = data as Point2D;
					  if(getGrid(v.x, v.y).getState()==IsoTileState.NORMAL){	  
				         getGrid(v.x, v.y).setState(IsoTileState.HOVER);
				      }
				  break;
				 case "IsoBound":
					  var i:int = 0;
					  var j:int = 0;
						for ( i = data.topGrid.x; i <= data.bottomGrid.x; i++) 
						{
							for ( j = data.topGrid.y; j <=data.bottomGrid.y ; j++) 
							{
								if(getGrid(i,j).getState()==IsoTileState.NORMAL){
								   getGrid(i, j).setState(IsoTileState.HOVER);
								}
							}
						}
				 break;
			  }
			}
		 
		public function clear(data:Object):void 
		{
			  switch(getClassName(data)) {
				  case "Point2D":
					  var v:Point2D = data as Point2D;
					  if(getGrid(v.x, v.y).getState()!=IsoTileState.NORMAL){	  
				         getGrid(v.x, v.y).setState(IsoTileState.NORMAL);
				      }
				  break;
				 case "IsoBound":
					  var i:int = 0;
					  var j:int = 0;
					  var bounddata:IsoBound = data as IsoBound;
						for ( i = bounddata.topGrid.x; i <= bounddata.bottomGrid.x; i++) 
						{
							for ( j = bounddata.topGrid.y; j <=bounddata.bottomGrid.y ; j++) 
							{
								if(getGrid(i,j).getState()!=IsoTileState.NORMAL){
								   getGrid(i, j).setState(IsoTileState.NORMAL);
								}
							}
						}
				 break;
			  }
			}	
			
		public function fillReset():void 
		{
			 for (var i:int = 0; i <_isoData.RowCount; i++) 
			   {
				   for (var j:int = 0; j <_isoData.ColumnCount ; j++) 
				   {
						 if(getGrid(i,j).getState()!=IsoTileState.NORMAL){
								   getGrid(i, j).setState(IsoTileState.NORMAL);
								}
				   }
			   }			
			}	
				
		/*******PreviewItem*************************************************/
		public function setPreviewItem(isoSprite:IsoSprite):void {
			if (!isInputIsoView(this)) return;
			 if  (this.getState() == IsoViewState.BUILD  ){
			      removePreviewItem();				  
			 }
			      _previewSprite = isoSprite;
				  _previewSprite.lock = false;
				  if ( (this.getState() == IsoViewState.BUILD  )
				        && _previewSprite != null ) {
				      
					  _previewSprite.x = this.stage.mouseX  - _previewSprite.width/2
			          _previewSprite.y = this.stage.mouseY -  _previewSprite.height/2	
				      
					 /* for (var i:int = 0; i <this.getAllIsoSprite().length; i++) 
					  {
						  var  isospr:IsoSprite
						if()
						IsoSprite(this.getAllIsoSprite()[i]).getGround().visible = true;
						//IsoSprite(this.getAllIsoSprite()[i]).setState(IsoSpriteState.INSIDE_VIEW);
					  }*/
					   for each(var  isospr:IsoSprite  in  this.getAllIsoSprite()) {
						      if (!isospr.lock) {
								    isospr.getGround().visible = true;
									isospr.setState(IsoSpriteState.INSIDE_VIEW);
								  }
						   }
			        }
					 _previewSprite.x = this.mouseX;
					 _previewSprite.y = this.mouseY;	
					 if(!_isoBuildSprite.contains(_previewSprite)){
					    _isoBuildSprite.addChild(_previewSprite);
					 }
			}
			
		public function getPreviewItem():IsoSprite {
			    return _previewSprite;
			}
			
		public function removePreviewItem():void {
			    if (_state == IsoViewState.MOVE && _previewSprite!=null ) {
					addIsoSprite(_previewSprite);
					_addIsoSprite.x = _addIsoSprite.getGroundRectangle().x
					_addIsoSprite.y = _addIsoSprite.getGroundRectangle().y
				}
				else if(_previewSprite!=null && _isoBuildSprite.contains(_previewSprite)){
					_isoBuildSprite.removeChild(_previewSprite);
					_previewSprite = null;
				}
			}	
			
			

		/********************************************************/
		
		public function set textCoordVisible(value:Boolean):void {
				_textCoordVisible = value;
			    for each( var item:IsoTile in _isoGidList) {
					  item.textCoordVisible = value;
				   }
			}
			
		public function get textCoordVisible():Boolean { return _textCoordVisible; }
	
		public function set gridVisible(value:Boolean):void 
		{
				_gridVisible = value;
			    for each( var item:IsoTile in _isoGidList) {
					  item.visible = value;
				   }
			}
			
		public function get gridVisible():Boolean { return _gridVisible; }
		
		/******MOUSE Logic Start**************************************/
		private var _selectPoint0:Point2D;
		private var _selectPoint1:Point2D;

		
		private function _mouseDownLogic(e:MouseEvent):void {
			     if (_isoScene.isoViewManager.getActiveIsoView() != this) return;
				 if (!isInputIsoView(e.target)) return;

				_SelectedIsoBound = null;
				 switch(getState()) {
					 case IsoViewState.SELECTGRID:
					  fillReset();
					  var target:IsoTile = IsoUtil.getIsoTileByPoint(this);
					  if (target != null) {
						   target.setState(IsoTileState.HOVER);
						   _selectPoint0 = new Point2D(target.row, target.column);
						   _selectPoint1 = new Point2D(target.row, target.column);
						  }else {
						   _selectPoint0 = null;  
						  }
					 break;
					}
		}
		 
			
		private function _mouseClickLogic(e:MouseEvent):void {
			    if (_isoScene.isoViewManager.getActiveIsoView() != this) return;   
			//ArthropodDebug.warning((_isoScene.isoViewManager.getActiveIsoView()==this).toString()+":::::::"+this.name+isInputIsoView(e.target)+"=="+getState());
			    if (!isInputIsoView(e.target)) return;
				switch(getState()) {
					  case IsoViewState.NORMAL:
					 	 EnterPickModeInClick(e)
					  break;
					  case IsoViewState.PICK:
					 	 EnterPickModeInClick(e)
					  break;
					  case IsoViewState.BUILD:
						 EnterBuildModeInClick(e);
					  break;
					  case IsoViewState.MOVE:
						 EnterMoveBuildModeInClick(e);
					  break;
					  case IsoViewState.REMOVE:
						 EnterReMoveModeInClick(e);
					  break;
					}
			}
			
		private function _mouseMoveLogic(e:MouseEvent):void {
			if (_isoScene.isoViewManager.getActiveIsoView() != this) return;
			if (!isInputIsoView(e.target)) return;
			
			switch(this.getState()) {
				case IsoViewState.NORMAL:
					EnterHoverModeInMove(e);
					break;
				case IsoViewState.BUILD:
					  EnterBuildModeInMove(e);
					break;
				case IsoViewState.MOVE:
                      EnterBuildModeInMove(e);
					break;
				case IsoViewState.SELECTGRID:
						if (_selectPoint0 == null) return;
						  var target:IsoTile = IsoUtil.getIsoTileByPoint(this);
						  if (target != null) {
						   _selectPoint1 = new Point2D(target.row, target.column);
						  }
						  fillReset();
						  fill(new IsoBound(_selectPoint0, _selectPoint1));
					break;
			  }
			 e.updateAfterEvent();
		}
		
		private function _mouseUpLogic(e:MouseEvent):void 
		{
			if (_isoScene.isoViewManager.getActiveIsoView() != this) return;
			if (!isInputIsoView(e.target)) return;
			switch(this.getState()) {
				case IsoViewState.BUILD:
				EnterBuildModeInUp(e);
					break;
				case IsoViewState.MOVE:
					EnterBuildModeInUp(e);
					break;
				case IsoViewState.SELECTGRID:
						if(_selectPoint0!=null){
						   fillReset();
						   _SelectedIsoBound = new IsoBound(_selectPoint0, _selectPoint1);
						   fill(_SelectedIsoBound);
						   this.dispatchEvent(new IsoViewEvent(IsoViewEvent.SELECTED));
						}
						_selectPoint0 = null;
						_selectPoint1 = null;
				    break;
			}
			
		   
		}
		/******MOUSE Logic End**************************************/
		
		public var prevHoverIsoSprite:IsoSprite;
		public var currentHoverIsoSprite:IsoSprite;
		
		/*=======EnterHoverModeInMove=============================*/	
		private function EnterHoverModeInMove(e:MouseEvent):void {
			   if (this.getState() == IsoViewState.NORMAL) {
				   var isp:IsoSprite = IsoUtil.getIsoSpriteByPoint(e,this);
					  if (isp != null)
					  {
						if (currentHoverIsoSprite != null) {
							prevHoverIsoSprite = currentHoverIsoSprite;
						 }
						currentHoverIsoSprite = isp;
						//currentHoverIsoSprite.alpha = 0.5;
						//if (prevHoverIsoSprite != null&& prevHoverIsoSprite!=currentHoverIsoSprite) _prevHoverIsoSprite.alpha = 1;
						
						if (currentHoverIsoSprite != prevHoverIsoSprite){
							this.dispatchEvent(new IsoViewEvent(IsoViewEvent.HOVER));
							}						
					  }else {
						 if(currentHoverIsoSprite!=null || prevHoverIsoSprite!=null){
						   this.dispatchEvent(new IsoViewEvent(IsoViewEvent.HOVEROUT));
						   currentHoverIsoSprite = null;
						   prevHoverIsoSprite = null;
						 }
						}
				   }
			}
		
		
		
		/*=======EnterPickModeInClick=============================*/	
		private function EnterPickModeInClick(e:MouseEvent):void {
			      var isp:IsoSprite = IsoUtil.getIsoSpriteByPoint(e,this);
				  if (isp != null)
				  {
					_pickIsoSprite = isp;
					this.dispatchEvent(new IsoViewEvent(IsoViewEvent.PICK));
				  }
			 }
		/*=======EnterBuildModeInClick=============================*/	
		private function EnterBuildModeInClick(e:MouseEvent):void{ 
			 if (_previewSprite == null) return;			           
				  _previewSprite.x = this.mouseX -  _previewSprite.getGroundRectangle().width / 2;
				  _previewSprite.y = this.mouseY -  _previewSprite.getGroundRectangle().height / 2;	
					  
			 var point:Point2D =  _checkGridExtend(_previewSprite.getIsoBound().row,
												   _previewSprite.getIsoBound().column);
			 if (point != null  && _isAllowBuilder(_extendIsoBound)) {
				 _previewSprite.setState(IsoSpriteState.INSIDE_VIEW)
				  fillReset();
				  _previewSprite.x = point.x;
				  _previewSprite.y = point.y;
				}else {
				 _previewSprite.setState(IsoSpriteState.OUTSIDE_VIEW);	
				}
			}
	
		/*=======EnterBuildModeInMove=============================*/		 
		private function EnterBuildModeInMove(e:MouseEvent):void{ 
				if (_previewSprite == null) return;
				  _previewSprite.x = this.mouseX -  _previewSprite.getGroundRectangle().width / 2;
				  _previewSprite.y = this.mouseY -  _previewSprite.getGroundRectangle().height / 2;	
			      
				  
				var point:Point2D =  _checkGridExtend(_previewSprite.getIsoBound().row,
													   _previewSprite.getIsoBound().column);
				                                        
			    if (point != null  && _isAllowBuilder(_extendIsoBound)) {
					  _previewSprite.setState(IsoSpriteState.INSIDE_VIEW)
					  fillReset();
					  _previewSprite.x = point.x;
					  _previewSprite.y = point.y;
					}else {
					  _previewSprite.setState(IsoSpriteState.OUTSIDE_VIEW);	
					}
			}	
				
		/*=======EnterBuildModeInUp=============================*/			
		private function EnterBuildModeInUp(e:MouseEvent):void {
			  switch(getState()) {
				    case IsoViewState.BUILD:
						if (_previewSprite != null && 
						_previewSprite.getStage() == IsoSpriteState.INSIDE_VIEW &&
						_isAllowBuilder(_extendIsoBound)
						) 
					   { 
						  _previewSprite.setIsoBound(_extendIsoBound);
						  addIsoSprite(_previewSprite);
					   }
					break;
				   case IsoViewState.MOVE:
						 if (_previewSprite != null && 
						_previewSprite.getStage() == IsoSpriteState.INSIDE_VIEW &&
						_isAllowBuilder(_extendIsoBound)
						) 
					    { 
						  MoveTo();
						  this.dispatchEvent(new IsoViewEvent(IsoViewEvent.MOVEISOSPRITE));
						  
						 /* setTimeout(function():void {
							     reSetMoveIsoSprite(_moveIsoSpriteOldIsoBound);
							  },5000)*/
					    }     
					break;
				  }
			}
			
			
			
		public function MoveTo():void {
				  _previewSprite.setIsoBound(_extendIsoBound);
				  addIsoSprite(_previewSprite);
				  this.setState(IsoViewState.NORMAL);
				  this.gridVisible = false;
			}
			
		public function	reSetMoveIsoSprite(bound:IsoBound):void {
			      _isoBuilderList.removeItem(_moveIsoSprite);
			      _moveIsoSprite.setIsoBound(bound);
				  addIsoSprite(_moveIsoSprite);
				  this.setState(IsoViewState.NORMAL);
				  this.gridVisible = false;
			}
		/*=======EnterReMoveModeInClick=============================*/			
		private function EnterReMoveModeInClick(e:MouseEvent):void {
			    var isp:IsoSprite = IsoUtil.getIsoSpriteByPoint(e,this);
				
				if (IsoConfig.AutoRemoveIsoSprite) {
					 if (isp != null)
					 removeIsoSprite(isp);
				    }else {
					 if (isp != null){
					   _removeIsoSprite = isp;
				       this.dispatchEvent(new IsoViewEvent(IsoViewEvent.REMOVEITEM_BEFORE));
					 }
				  }
			}
		
		/*=======EnterMoveBuildModeInClick=============================*/		
		private function EnterMoveBuildModeInClick(e:MouseEvent):void {
		          var isp:IsoSprite = IsoUtil.getIsoSpriteByPoint(e,this);
				  if (isp != null && isp.isDrag)
				  {
					_moveIsoSprite = isp;
					_moveIsoSpriteOldIsoBound =  isp.getIsoBound().clone();
					_isoBuilderList.moveItem(isp);
					setPreviewItem(isp);
					isp.getGround().visible = true;
					isp.setState(IsoSpriteState.INSIDE_VIEW);
					 _moveIsoSprite.x = this.mouseX -  _moveIsoSprite.getGroundRectangle().width / 2;
				     _moveIsoSprite.y = this.mouseY -  _moveIsoSprite.getGroundRectangle().height / 2;					 
					 _isoBuilderList.removeItem(_moveIsoSprite);
				  }
			}
			

		/**
		 * 检查是否允许建造建筑
		 * @param	data
		 * @return
		 */
		private function _isAllowBuilder(data:Object):Boolean {
			var _result:Boolean=true;			  
			  switch(getClassName(data)) {
				    case  "Point2D":
						var v:Point2D = data as Point2D;
						 if(IsoBaseData(_isoData.getCell(v.x, v.y.toString())).IsBuilder) _result = false;
						break;
				    case "IsoBound":
						 data = IsoBound(data);
				        for (var i:int = data.topGrid.x; i <=data.bottomGrid.x; i++) 
						  {
							  for (var j:int = data.topGrid.y; j <=data.bottomGrid.y; j++)
							  {		
								  /**
								   * IsoBaseData 确定能不能通过
								   */
								  if (IsoBaseData(_isoData.getCell(i, j.toString())).IsBuilder) 
								  {
									  _result = false; 
								  }
							  }
						  }
					break;
				}
			  return _result;
			}		
		 
		/*==========================================================================*/
		/**
		 * 检测扩展格子，符合扩展返回地面格子矩形的左上角
		 */
		private var _extendIsoBound:IsoBound;
		private function _checkGridExtend(row:int,column:int):Point2D 
		{
			var target:IsoTile = IsoUtil.getIsoTileByPoint(this);
			if (target != null) {
				_extendIsoBound = IsoUtil.extendGrid(new Point2D(target.row, target.column), row,column);
				//if (!containBound(_extendIsoBound)) return null;
				if (_extendIsoBound.isOutside(_editBound)) {
				    return null;
				  }else{
				   var r:Rectangle = IsoMath.getIsoBoundRectangle(this, _extendIsoBound);
				   if (r == null) return null;
				   return new Point2D(r.x, r.y);
				 }
			 }
			return null;
		}	
			
		/*********************************************************************************/
		private var _pickIsoSprite:IsoSprite;
		public function get PickIsoSpriteItem():IsoSprite { return _pickIsoSprite; }
		
		
		private var _addIsoSprite:IsoSprite;
		public function get AddIsoSpriteItem():IsoSprite { return _addIsoSprite; }
		private var _moveIsoSpriteOldIsoBound:IsoBound;
		private var _moveIsoSprite:IsoSprite;
		public function get MoveIsoSpriteItem():IsoSprite { return _moveIsoSprite; }
		
		
		private var _removeIsoSprite:IsoSprite;
		public function get RemoveIsoSpriteItem():IsoSprite { return _removeIsoSprite; }
		private var _SelectedIsoBound:IsoBound;
		public function get SelectedIsoBound():IsoBound { return _SelectedIsoBound; }
		public function  removeSelectedIsoBound():void { _SelectedIsoBound = null; }
		
		
		private  function isInputIsoView(target:*):Boolean {
			return  target == this
			// return  e.target is IsoView &&  e.target == this;
			// return  ( _isoScene.isoViewManager.getActiveIsoView()==this && e.target is IsoView &&  e.target == this)
			}
		 
		 
		/********************************************************/
		
		public function dispose():void {
			  //do someting
			  //event  isRemoved
			  for each ( var  item:IsoSprite in _isoBuilderList.getAllIsoSprite()) {
				      item.dispose();
				  }
			}
		
		
		
		private var _autoSort:Boolean;
		public function set autoSort(value:Boolean):void {
			     _autoSort = value;
				 _isoBuilderList.autoSort = value;
			}
		public function get autoSort():Boolean { return _autoSort; }
	}

}